import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

export enum LangKey {
  EN = 'en',
  ZH_HANS = 'zh-Hans',
  ZH_HANT = 'zh-Hant',
}
const CHS = ['zh-Hans', 'zh-CN', 'zh-SG', 'zh-MY', 'zh'];
const CHT = ['zh-Hant', 'zh-TW', 'zh-HK', 'zh-MO'];
const DEFAULT_LANG_KEY = (() => {
  if (navigator) {
    const lang = navigator.language;
    if (CHT.includes(lang)) {
      return LangKey.ZH_HANT;
    } else if (CHS.includes(lang)) {
      return LangKey.ZH_HANS;
    }
  }
  return LangKey.EN;
})();

export async function changeLanguage(langKey: LangKey) {
  const resource = await import(`./locales/${langKey}.json`);
  await i18n
    .addResourceBundle(langKey, 'translation', resource.default)
    .changeLanguage(langKey);
}

i18n
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    resources: {}, // 語言檔為動態載入所以初始為空
    lng: DEFAULT_LANG_KEY, // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources
    interpolation: {
      escapeValue: false, // react already safes from xss
    },
  });

changeLanguage(DEFAULT_LANG_KEY);

export default i18n;
